<template>
  <div class="program">
    <div class="video" v-if="userInfo">
      <div class="con">
        <div>
          <el-alert :title="userInfo.role == 2 ? '这里是考生页面' : '这里是面试官页面'" :closable="false" type="warning">
          </el-alert>
          <el-tag type="success">我：{{ userInfo.role == 2 ? userInfo.studentName : userInfo.adminName }}</el-tag>
          <div ref="localvideoRef" class="localVideo">
            <div class="agora-video">
              <StreamPlayer :stream="localStream" :domId="localStream.getId()" v-if="localStream"></StreamPlayer>
            </div>
          </div>
        </div>
        <div>
          <el-tag>对方</el-tag>
          <div ref="remotevideoRef" class="remoteVideo">
            <div class="agora-video">
              <div class="agora-video">
                <StreamPlayer class="video" :key="index" v-for="(remoteStream, index) in remoteStreams" :stream="remoteStream"
                  :domId="remoteStream.getId()"></StreamPlayer>
              </div>
            </div>
          </div>
        </div>
        <div class="control">
          <div>
            <el-button size="small" type="success" plain round @click="joinEvent">join</el-button>
            <el-button size="small" type="warning" plain round @click="leaveEvent">leave</el-button>
          </div>
        </div>
      </div>
    </div>
    <div class="code" ref="codeRef" v-if="userInfo.role == 2">
      <CodeAreaVue></CodeAreaVue>
    </div>
    <div class="codePlay" v-else>
      <div class="agora-video">
        <StreamPlayer class="screen" :key="index" v-for="(screenStream, index) in remoteScreenStreams" :stream="screenStream"
          :domId="screenStream.getId()"></StreamPlayer>
      </div>
    </div>
  </div>
</template>

<script>
import RTCClient from "./agora-rtc-client";
import AgoraRTC from 'agora-rtc-sdk';
import StreamPlayer from "./stream-player";
import CodeAreaVue from "./CodeArea.vue";
import { log } from './utils';
import { mapState } from 'vuex'
import * as rrweb from "rrweb";
import RrwebPlayer from "rrweb-player";
export default {
  components: {
    StreamPlayer,
    CodeAreaVue
  },

  data() {
    return {
      screenRtc: new RTCClient(),
      rtc: new RTCClient(), //音视频RTC
      option: {
        // Pass your App ID here.
        appid: "3d38246f5aee45de8bd8d57a536d94eb",
        // Set the channel name.
        channel: "ch2",
        // Pass your temp token here.
        token: "0063d38246f5aee45de8bd8d57a536d94ebIACFcLo6L632am6dktOqf65KNGagNbv/5ZZroKHCoWtXD0QcI9AAAAAAEAASVDxD3RKCYgEAAQDdEoJi",
        // Set the user ID.
        uid: this.$store.state.uid,
      },
       screenOption: {
        // Pass your App ID here.
        appid: "c38b4249c8944775ae11d3f31b083d54",
        // Set the channel name.
        channel: "ch2",
        // Pass your temp token here.
        token: "006c38b4249c8944775ae11d3f31b083d54IADt1H4VHZC7NJ/eTAaTDTwm9+PytgTpVRS6u+lWM6zctEQcI9AAAAAAEAASVDxDGjOCYgEAAQAaM4Ji",
        // Set the user ID.
        uid: this.$store.state.uid,
      },
      showJoin: false,
      localStream: null,
      remoteStreams: [],
      localScreenStream: null,
      remoteScreenStreams: [],
      temp: [],
      events: null
    }
  },

  computed: {
    ...mapState({
      userInfo: state => state.userInfo
    })
  },

  created() {
    console.log(this.userInfo);
    // let codeRtc = this.codeRtc
    // codeRtc.on('stream-added', (evt) => {
    //   console.log('stream add');
    //   let { stream } = evt
    //   log("[agora] [stream-added] stream-added", stream.getId())
    //   codeRtc.client.subscribe(stream) //subscribe  
    // })

    // codeRtc.on('stream-subscribed', (evt) => {
    //   let { stream } = evt
    //   console.log(stream);
    //   // log("[agora] [stream-subscribed] stream-added", stream.getId())
    //   // if (!this.remoteStreams.find((it) => it.getId() === stream.getId())) {
    //     this.temp.push(stream)
    //     if (this.userInfo.role == 2) {
    //       console.log('学生');
    //       this.remoteStreams = [this.temp[0]]
    //     } else {
    //       this.remoteStreams = this.temp
    //     }
    //     console.log(this.remoteStreams);
    //   // }
    // })

    // codeRtc.on('stream-removed', (evt) => {
    //   let { stream } = evt
    //   log('[agora] [stream-removed] stream-removed', stream.getId())
    //   this.remoteStreams = this.remoteStreams.filter((it) => it.getId() !== stream.getId())
    // })

    let rtc = this.rtc
    let screenRtc = this.screenRtc
    rtc.on('stream-added', (evt) => {
      rtc.on('stream-added', (evt) => {
        console.log('stream add');
        let { stream } = evt
        log("[agora] [stream-added] stream-added", stream.getId())
        rtc.client.subscribe(stream) //subscribe  
      })
    })

    rtc.on('stream-subscribed', (evt) => {
      this.$message.success('订阅到video了');
      let { stream } = evt
      console.log(stream);
      // log("[agora] [stream-subscribed] stream-added", stream.getId())
      if (!this.remoteStreams.find((it) => it.getId() === stream.getId())) {
        this.remoteStreams.push(stream)
        console.log(this.remoteStreams);
      }
    })

    rtc.on('stream-removed', (evt) => {
      let { stream } = evt
      log('[agora] [stream-removed] stream-removed', stream.getId())
      this.remoteStreams = this.remoteStreams.filter((it) => it.getId() !== stream.getId())
    })
    screenRtc.on('stream-added', (evt) => {
      console.log('stream add');
      let { stream } = evt
      log("[agora] [stream-added] stream-added", stream.getId())
      screenRtc.client.subscribe(stream) //subscribe  
    })

    screenRtc.on('stream-subscribed', (evt) => {
      this.$message.success('订阅到screen了');
      let { stream } = evt
      console.log(stream);
      // log("[agora] [stream-subscribed] stream-added", stream.getId())
      if (!this.remoteScreenStreams.find((it) => it.getId() === stream.getId())) {
        this.remoteScreenStreams.push(stream)
        console.log('------------------------------------------');
      }
    })

    screenRtc.on('stream-removed', (evt) => {
      let { stream } = evt
      log('[agora] [stream-removed] stream-removed', stream.getId())
      this.remoteScreenStreams = this.remoteScreenStreams.filter((it) => it.getId() !== stream.getId())
    })
  },

  mounted() {
  },

  updated() {
    // this.startBasicCall()
  },

  methods: {
    joinEvent() {
      if (!this.option.appid) {
        this.judge('Appid')
        return
      }
      if (!this.option.channel) {
        this.judge('Channel Name')
        return
      }
      this.rtc.joinChannel(this.option).then(() => {
        this.$message({
          message: 'Join Success',
          type: 'success'
        });
        this.rtc.publishStream('video').then(() => {//创建音视频流 并且进行推流
          this.$message({
            message: 'Publish Success',
            type: 'success'
          });
          this.localStream = this.rtc.localStream// 音视频流对象

        }).catch((err) => {
          this.$message.error('Publish Failure');
          log('publish local error', err)
        })

      }).catch((err) => {
        this.$message.error('Join video Failure');
        log('join channel error', err)
      })
      if (this.userInfo.role == 2) {
        this.$message.success('当前是学生端');
        this.screenRtc.joinChannel(this.screenOption).then(() => {
          this.$message({
            message: 'Join screen Success',
            type: 'success'
          });
          this.screenRtc.publishStream('screen').then(() => {//创建音视频流 并且进行推流
            this.$message({
              message: 'Publish screen Success',
              type: 'success'
            });

          }).catch((err) => {
            this.$message.error('Publish screen Failure');
            log('publish screen error', err)
          })

        }).catch((err) => {
          this.$message.error('Join Failure');
          log('join channel error', err)
        })
      }

      this.showJoin = true
    },
    leaveEvent() {
      this.showJoin = false
      this.rtc.leaveChannel().then(() => {//离开频道
        this.$message({
          message: 'Leave Success',
          type: 'success'
        });
      }).catch((err) => {
        this.$message.error('Leave Failure')
        log('leave error', err)
      })
      this.localStream = null
      this.remoteStreams = []
    },
    judge(detail) {
      this.$notify({
        title: 'Notice',
        message: `Please enter the ${detail}`,
        position: 'top-left',
        type: 'warning'
      });
    },
    // ——————————————————


  }
};
</script>

<style scope>
.el-tag {
  margin: 10px;
}

.program {
  box-sizing: border-box;
  width: 100%;
  height: 100%;
  display: flex;
}

.video {
  padding: 10px 25px;
  width: 20%;
  background-color: aliceblue
}

.con {}

.control>div {
  padding: 38px;
}

.input {
  width: 100px;
}

.remoteVideo {
  width: 230px;
  height: 160px;
  background-color: antiquewhite;
}

.localVideo {
  width: 230px;
  height: 160px;
  background-color: antiquewhite;
}

.agora-video {
  width: 230px;
  height: 160px;
  margin: auto;


}

.code {
  width: 80%;
  background-color: #fffffe;
}

.canvas {
  height: 100%;
  width: 100%
}
</style>